package com.example.backend.service;


import com.example.backend.mapper.CardInfoMapper;
import com.example.backend.mapper.TradeInfoMapper;
import com.example.backend.model.CardInfo;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Pattern;

import com.example.backend.model.TradeInfo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@MapperScan("com.example.backend.mapper")
public class CardInfoService {
    @Autowired private CardInfoMapper cardInfoMapper;
    private static final Pattern CARD_ID_PATTERN = Pattern.compile("^10103576\\d{8}$");
    private static final Pattern PASS_PATTERN = Pattern.compile("^\\d{6}$");
    private static final BigDecimal MIN_AMOUNT = new BigDecimal("1.00");

    // 生成符合规则的卡号（前8位10103576+8位随机数）
    private String generateCardID() {
        String prefix = "10103576";
        String suffix = new Random().ints(8, 0, 10)
                .mapToObj(String::valueOf)
                .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
                .toString();
        return prefix + suffix;
    }

    @Transactional
    public String addCardInfo(CardInfo cardInfo) {
        // 验证参数
        validateCardInfo(cardInfo);
        // 生成卡号
        String cardID = generateCardID();
        cardInfo.setCardID(cardID);
        // 设置默认值
        if (cardInfo.getPass() == null || !PASS_PATTERN.matcher(cardInfo.getPass()).matches()) {
            cardInfo.setPass("888888");
        }
        if (cardInfo.getOpenDate() == null) {
            cardInfo.setOpenDate(new Timestamp(System.currentTimeMillis()));
        }
        if (cardInfo.getCurID() == null) {
            cardInfo.setCurID("RMB");
        }
        if (cardInfo.getIsReportLoss() == null) {
            cardInfo.setIsReportLoss("否");
        }
        // 插入数据库
        cardInfoMapper.insertCardInfo(cardInfo);
        return cardID;
    }

    @Transactional
    public int deleteCardInfoByCardID(String cardID) {
        return cardInfoMapper.deleteCardInfoByCardID(cardID);
    }

    @Transactional
    public int updateCardInfoByCardID(CardInfo cardInfo) {
        // 验证卡号格式
        if (cardInfo.getCardID() != null && !CARD_ID_PATTERN.matcher(cardInfo.getCardID()).matches()) {
            throw new IllegalArgumentException("卡号格式错误，必须为16位数字且前8位为10103576");
        }
        // 验证密码格式
        if (cardInfo.getPass() != null && !PASS_PATTERN.matcher(cardInfo.getPass()).matches()) {
            throw new IllegalArgumentException("密码必须为6位数字");
        }
        // 验证金额
        if (cardInfo.getOpenMoney() != null && cardInfo.getOpenMoney().compareTo(MIN_AMOUNT) < 0) {
            throw new IllegalArgumentException("开户金额不得小于1元");
        }
        if (cardInfo.getBalance() != null && cardInfo.getBalance().compareTo(MIN_AMOUNT) < 0) {
            throw new IllegalArgumentException("账户余额不得小于1元");
        }
        return cardInfoMapper.updateCardInfoByCardID(cardInfo);
    }

    public CardInfo getCardInfoByCardID(String cardID) {
        return cardInfoMapper.selectCardInfoByCardID(cardID);
    }

    public List<CardInfo> searchCardInfoByCardIDLike(String cardID) {
        return cardInfoMapper.selectCardInfoByCardIDLike(cardID);
    }

    public List<CardInfo> searchCardInfoByOpenMoneyRange(Map<String, Object> params) {
        return cardInfoMapper.selectCardInfoByOpenMoneyRange(params);
    }

    // 参数验证方法
    private void validateCardInfo(CardInfo cardInfo) {
        if (cardInfo.getSavingID() == null) {
            throw new IllegalArgumentException("存款类型ID不能为空");
        }
        if (cardInfo.getCustomerID() == null) {
            throw new IllegalArgumentException("客户ID不能为空");
        }
        if (cardInfo.getOpenMoney() == null || cardInfo.getOpenMoney().compareTo(MIN_AMOUNT) < 0) {
            throw new IllegalArgumentException("开户金额不得小于1元");
        }
        if (cardInfo.getBalance() == null || cardInfo.getBalance().compareTo(MIN_AMOUNT) < 0) {
            throw new IllegalArgumentException("账户余额不得小于1元");
        }
    }

    @Transactional
    public boolean deposit(String cardID, BigDecimal depositMoney) {
        // 查询银行卡信息
        CardInfo cardInfo = cardInfoMapper.selectCardInfoByCardID(cardID);
        if (cardInfo == null) {
            return false; // 银行卡不存在
        }

        // 计算存款后的余额
        BigDecimal newBalance = cardInfo.getBalance().add(depositMoney);
        cardInfo.setBalance(newBalance);

        // 更新银行卡余额
        int updateResult = cardInfoMapper.updateCardInfoByCardID(cardInfo);
        if (updateResult == 0) {
            return false; // 更新失败
        }

        // 记录交易信息
        TradeInfo tradeInfo = new TradeInfo();
        tradeInfo.setTradeDate(new Timestamp(System.currentTimeMillis()));
        tradeInfo.setTradeType("存款");
        tradeInfo.setCardID(cardID);
        tradeInfo.setTradeMoney(depositMoney);
        tradeInfo.setRemark("正常存款");
        int insertResult = TradeInfoMapper.insertTradeInfo(tradeInfo);
        if (insertResult == 0) {
            return false; // 记录交易信息失败
        }

        return true; // 存款成功
    }
}